 
package com.zdkj.subway.rca.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;

import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.rca.entity.ViewCkDataauditJiehangcash;
import com.zdkj.subway.rca.mapper.ViewCkDataauditJiehangcashMapper;
import com.zdkj.subway.rca.service.ViewCkDataauditJiehangcashService;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import com.zdkj.subway.rca.util.MyDateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * VIEW
 *
 * @author stw
 * @date 2020-11-01 11:06:31
 */
@Service
public class ViewCkDataauditJiehangcashServiceImpl extends ServiceImpl<ViewCkDataauditJiehangcashMapper, ViewCkDataauditJiehangcash> implements ViewCkDataauditJiehangcashService {
    private static final Logger log = LoggerFactory.getLogger(ViewCkDataauditJiehangcashServiceImpl.class);
    /**
     * 产生数据
     * @return
     */
    @Override
    public Boolean generate(String startDate,String endDate) throws Exception {

        List<String> listDate = MyDateUtil.getDatesBetweenTwoDate(startDate,endDate);

        //根据日期范围获取数据list
        List<Map<String,Object>> dataListA = this.baseMapper.getDataListA(startDate,endDate);
        List<Map<String,Object>> dataListB = this.baseMapper.getDataListB(startDate,endDate);

        List<ViewCkDataauditJiehangcash> updaeList = new ArrayList<>();
        List<ViewCkDataauditJiehangcash> insertList = new ArrayList<>();

        PigxUser user = SecurityUtils.getUser();

        //循环时间段内每一天
        for(String tradeDate : listDate) {
            ViewCkDataauditJiehangcash insertObj = new ViewCkDataauditJiehangcash();
            insertObj.setTradeDate(LocalDate.parse(tradeDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));

            //数据库老的
            ViewCkDataauditJiehangcash dbViewCkDataauditJiehangcash = this.getOne(Wrappers.query(insertObj));
            if (dbViewCkDataauditJiehangcash != null){
                insertObj.setId(dbViewCkDataauditJiehangcash.getId());
            }

            insertObj.setJiehangMoney(getData(tradeDate,"JIEHANG_MONEY",dataListA));
            insertObj.setCashMoney(getData(tradeDate,"CASH_MONEY",dataListB));
            insertObj.setDiffMoney(insertObj.getJiehangMoney().subtract(insertObj.getCashMoney()));

            insertObj.setDeptId(user.getDeptId());
            insertObj.setCreatorId(user.getId());
            insertObj.setCreatorName(user.getNikeName());
            if(insertObj.getId() != null){
                updaeList.add(insertObj);
            } else {
                insertList.add(insertObj);
            }

        }
        boolean flag = false;
        boolean flag2 = false;
        if(!updaeList.isEmpty()){
            flag = this.updateBatchById(updaeList);
        }
        if(!insertList.isEmpty()){
            flag2 = this.saveBatch(insertList);
        }
        return  flag || flag2;
    }
    private BigDecimal getData(String tradeDate, String key, List<Map<String,Object>> dataList){
        if(dataList == null || dataList.isEmpty()) {
            return new BigDecimal(0);
        }
        for(Map<String,Object> map : dataList) {
            if(tradeDate.equals(DateUtils.format((Date)map.get("TRADE_DATE"),"yyyy-MM-dd"))) {
                return (BigDecimal)map.get(key);
            }
        }
        return new BigDecimal(0);
    }
    /**
     * 导出
     * @param
     * @return
     * @throws IOException
     */
    @Override
    public void exportExcel(String startDate, String endDate, HttpServletResponse response) {
        ViewCkDataauditJiehangcash viewCkDataauditJiehangcash = new ViewCkDataauditJiehangcash();
        List<ViewCkDataauditJiehangcash> records  = this.list(Wrappers.query(viewCkDataauditJiehangcash).lambda()
                .ge(StringUtils.isNotEmpty(startDate), ViewCkDataauditJiehangcash::getTradeDate, startDate)
                .le( StringUtils.isNotEmpty(endDate),ViewCkDataauditJiehangcash::getTradeDate, endDate)
                .orderByDesc(ViewCkDataauditJiehangcash::getTradeDate));
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("解行金额与车站现金缴款单据复核", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/ViewCkDataauditJiehangcashExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("解行金额与车站现金缴款单据复核").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);

            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出解行金额与车站现金缴款单据复核错误");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }

            }
        }
    }
}
